package com.mastercard.assets.web.struts.actions;

import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mastercard.assets.jpa.TblAsset;
import com.mastercard.assets.jpa.TblUsuario;
import com.mastercard.assets.util.dao.MasterCardDAO;
import com.mastercard.assets.web.struts.forms.AssetBuscarForm;
import com.mastercard.assets.web.util.to.UserLogin;

public class AssetsBuscarRegional
        extends
		Action
{
    
    public ActionForward execute(
							ActionMapping mapping , 
							ActionForm form ,
							HttpServletRequest request , 
							HttpServletResponse response )
		throws 
			IOException , 
			ServletException
    {
        
        HttpSession session = request.getSession( ) ;
		
		// en caos de null
		if( session == null )
			return mapping.findForward( "noLogin" ) ;
		
		// toma el userLogin
		UserLogin user = ( UserLogin ) session.getAttribute( "UserLogin" ) ;
                int roleId = user.getActualRoleId( ) ;
		int cveUsuario = user.getCveUsuario() ;
		TblUsuario userData = MasterCardDAO.findUserById( cveUsuario ) ;
                String codigoPais = userData.getTblPais().getCodigo();
                String nombrePais = userData.getTblPais().getNombre();
                int cvePais = userData.getTblPais().getCvePais();
		// en caso de null
		if( user == null ) {
                    MasterCardDAO.closeEntityManager( ) ;
                    return mapping.findForward( "noLogin" ) ;
                }
			
                
                try
		{
			// convierte el form y toma la clave
			AssetBuscarForm f = ( AssetBuscarForm ) form ;
			
			int cve = f.getCveAsset( ) ;
			
//			System.out.println( "Cve a buscar::: " + cve ) ;
			
			TblAsset item = MasterCardDAO.findAssetById( cve ) ;
			
//			System.out.println( "Asset encontrado::: " + item ) ;
			
			if( item == null )
				return mapping.findForward( "NoItemFinded" ) ;
			
			request.setAttribute( "ItemFinded" , item ) ;
			request.setAttribute( "roleId" , roleId ) ;
			request.setAttribute( "cvePais" , cvePais ) ;
			request.setAttribute( "nombrePais" , nombrePais ) ;
			request.setAttribute( "codigoPais" , codigoPais ) ;
			request.setAttribute( "IdSearched" , new Integer( cve ) ) ;
			
		}catch( Exception e )
		{
                    MasterCardDAO.closeEntityManager( ) ;
			user.setMessageError( e.getMessage( ) ) ;
		} 

                MasterCardDAO.closeEntityManager( ) ;    
                return mapping.findForward( "success" ) ;
        
    }
    
}
